package com.example.dao;

import com.example.entity.Student;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.UUID;

/**
 * 学生对象数据访问类
 * @author 李平
 * @date 2022-4-30
 */
@Component
public class StudentDao {

    @Autowired
    @Qualifier("apiJdbcTemplate")
    protected JdbcTemplate jdbcTemplate;

    private static final Logger log = LoggerFactory.getLogger(StudentDao.class.toGenericString());

    /**
     * 通过电话号码和密码查询学生信息
     * @param phone
     * @param password
     * @return Student
     */
    public Student getStudentByPAndP(String phone, String password){

        String sql = String.format("SELECT * FROM student where phone='%s' and password='%s'", phone, password);
        List<Student> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Student.class));
        log.info(sql);
        return query == null || query.size() == 0 ? null : query.get(0);
    }

    /**
     * 通过电话号码查询学生信息
     * @param phone
     * @return Student
     */
    public Student getStudentByPhone(String phone){
        String sql = String.format("SELECT * FROM student where phone='%s'", phone);
        List<Student> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Student.class));
        log.info(sql);
        return query == null || query.size() == 0 ? null : query.get(0);
    }

    /**
     * 插入学生对象
     * @param student
     * @return Boolean
     */
    public Boolean addStudent(Student student){
        String sql = String.format("INSERT INTO student(id,phone,password,code) values('%s','%s','%s','%s')",
                student.getId(),student.getPhone(),student.getPassword(),student.getCode());
        log.info(sql);
        jdbcTemplate.execute(sql);
        return true;
    }
}
